package test

import (
	"errors"
	"fmt"
	"os"

	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"

	"cvevulner/common"
	"cvevulner/models"
	"cvevulner/util"
)

func QueryOriginCveExcelData() ([]models.OriginExcel, int64, error) {
	o := orm.NewOrm()
	var coe []models.OriginExcel
	num, err := o.Raw("select cve_id,cve_num,cve_url, cve_version, pack_name," +
		"score_type,nvd_score,cve_level,cve_desc,repair_time,vector_value,attack_vector,access_vector,attack_complexity," +
		"access_complexity,privilege_required,user_interaction,scope,confidentiality,integrity,availability,authentication," +
		"cve_status,create_time from cve_origin_excel GROUP BY pack_name").QueryRows(&coe)
	if err == nil && num > 0 {
		logs.Info("cve_origin_excel 查询结果： ", num)
	} else {
		logs.Info("当前无新增或者更新的cve, cur_time:", common.GetCurTime(), "err: ", err)
	}
	return coe, num, err
}

func UpdateExcelDataPkName(originPackName, packName string) (id int64) {
	o := orm.NewOrm()
	_ = o.Raw("UPDATE cve_origin_excel SET pack_name = ?"+
		" WHERE pack_name = ?", packName, originPackName).QueryRow()
	return
}

func CreateRepo() {
	coe, num, err := QueryOriginCveExcelData()
	if err == nil && num > 0 {
		for _, qc := range coe {
			PostRepo(qc.PackName)
		}
	}
}

func PostRepo(packName string) error {
	url := "https://gitee.com/api/v5/user/repos"
	accessToken := os.Getenv("GITEE_TOKEN")
	requestBody := fmt.Sprintf(`{
			"access_token": "%s",
			"name": "%s", 
			"has_issues": "true",
			"has_wiki": "true",
			"can_comment": "true",
			"auto_init": "true",
			"path": "%s",
			"private": "false"
			}`, accessToken, packName, packName)
	logs.Info("isssue_body: ", requestBody)
	resp, err := util.HTTPPost(url, requestBody)
	if err != nil {
		logs.Error("创建", packName, "失败, err: ", err)
		return err
	}
	if _, ok := resp["id"]; !ok {
		logs.Error("创建issue 失败, err: ", ok, "url: ", url)
		return errors.New("创建仓库失败")
	}
	errb := CreateBrand(packName)
	logs.Info(errb)
	return nil
}

func CreateBrand(packName string) error {
	url := "https://gitee.com/api/v5/repos/zhangjianjun_code/" + packName + "/branches"
	accessToken := os.Getenv("GITEE_TOKEN")
	requestBody := fmt.Sprintf(`{
			"access_token": "%s",
			"refs": "master", 
			"branch_name": "openEuler-20.03-LTS"
			}`, accessToken)
	logs.Info("isssue_body: ", requestBody)
	resp, err := util.HTTPPost(url, requestBody)
	if err != nil {
		logs.Error("创建分支：openEuler-20.03-LTS", packName, "失败, err: ", err)
		return err
	}
	if _, ok := resp["id"]; !ok {
		logs.Error("创建分支：openEuler-20.03-LTS 失败, err: ", ok, "url: ", url)
		return errors.New("创建分支失败")
	}

	return nil
}

func Init() {
	CreateRepo()
}
